import json
from Model.environment import *
from Model.user import *
from Model.transport import TransportOrder
from Model.sales import SalesOrder
from Model.logistics import Logistics
from Model.other import *
from Model.sql import Sql
from common.log import logger


carWeight = 3
transport: TransportOrder = None
sales: SalesOrder = None
entry = None
puser = None
auser = None
sql = None
cargo = None
storehouse_dict = None
env = None
# 合约规则
hy_rule = None
one_hy_rule = None
two_hy_rule = None
# 自提规则
zt_rule = None
# 配送规则
ps_rule = None
# 物料
cargo_dict = None


def update_env(request):
    global env
    env_str = request.POST.get('type')
    env = Environment(env_str, logger)
    return {
        "status": env.status
    }


def connect_sql(request):
    global sql, env
    sql = Sql(env)
    return {
        "status": "已连接SQL"
    }


def pc_login(request):
    global env, puser
    # PC端登录
    username = request.POST.get('username')
    password = request.POST.get('password')
    puser = PcUser(username, password, env)
    puser.login()
    if puser.token != "":
        res_status = f"{username}已登录"
    else:
        res_status = f"{username}登录失败"
    return {
        "status": res_status
    }


def app_login(request):
    global env, auser
    # APP端登录
    username = request.POST.get('username')
    password = request.POST.get('password')
    auser = AppUser(username, password, env)
    auser.login()
    if auser.token != "":
        res_status = f"{username}已登录"
    else:
        res_status = f"{username}登录失败"
    return {
        "status": res_status
    }


def sales_order_query(request):
    # 销售订单查询
    global env, puser, auser, sales, sql, logger
    sales_order_no = request.POST.get('order_no')
    sales = SalesOrder(env, puser, auser, sales_order_no, sql, logger)
    sales.sales_order_query()
    if sales.code == 0:
        return {
            "status": sales.status
        }
    if sales.info["orderTypeName"] == "未知":
        sales.status = "物料未配置"
        return {
            "status": sales.status
        }
    if sales.info["tmsStatusName"] == "未审核":
        sales.status = "销售端订单未审核"
        return {
            "status": sales.status
        }
    if sales.info["deliveryStatusTypeName"] == "未分配":
        sales.status = "订单未分配"
        return {
            "status": sales.status
        }

    return {
        "status": sales.status
    }


def set_cargo(request):
    # 设置物料
    global cargo, sales

    cargo_type = request.POST.get('cargo_type')
    store_type = request.POST.get('store_type')
    items = sales.goods
    for item in items:
        goods_no = item["goodsNo"]
        unitWeight = item["unitWeight"]
        cargo.set_cargo(goods_no, unitWeight, cargo_type,
                        cargo_type, store_type)
        if cargo.code == 0:
            return cargo.status
    return {
        "status": cargo.status
    }


def set_one_hy_rule(request):
    # 启用一级合约规则
    global sales, env, puser, hy_rule, one_hy_rule, two_hy_rule
    if type(hy_rule) is OneLevelTreatyRule:
        return "已是一级合约规则"
    if type(hy_rule) is TwoLevelTreatyRule:
        # 关闭二级合约规则
        hy_rule.set_treaty_config(False, two_hy_rule.enableProductRoute,
                                  two_hy_rule.mainCarrierSplitValue, two_hy_rule.mainCarrierOrderAllotValue,
                                  two_hy_rule.actualCarrierOrderAllotValue, two_hy_rule.actualCarrierSplitValue,
                                  two_hy_rule.actualCarrierOrderAllotVehicleCount, two_hy_rule.actualCarrierSplitWeightValue,
                                  two_hy_rule.enableActualCarrierWeightAllot, two_hy_rule.mainCarrierAllocationRatios)
    # 启用一级合约规则
    hy_rule = OneLevelTreatyRule(env, puser, logger)
    hy_rule.set_treaty_config(True, one_hy_rule.enableProductRoute)
    return {
        "status": hy_rule.status
    }


def set_two_hy_rule(request):
    # 启用二级合约规则
    global sales, env, puser, hy_rule, one_hy_rule, two_hy_rule
    if type(hy_rule) is TwoLevelTreatyRule:
        return "已是二级合约规则"
    if type(hy_rule) is OneLevelTreatyRule:
        # 关闭一级合约规则
        hy_rule.set_treaty_config(False, one_hy_rule.enableProductRoute)
    # 启用二级合约规则
    hy_rule = TwoLevelTreatyRule(env, puser, logger)
    hy_rule.set_treaty_config(True, two_hy_rule.enableProductRoute,
                              two_hy_rule.mainCarrierSplitValue, two_hy_rule.mainCarrierOrderAllotValue,
                              two_hy_rule.actualCarrierOrderAllotValue, two_hy_rule.actualCarrierSplitValue,
                              two_hy_rule.actualCarrierOrderAllotVehicleCount, two_hy_rule.actualCarrierSplitWeightValue,
                              two_hy_rule.enableActualCarrierWeightAllot, two_hy_rule.mainCarrierAllocationRatios)
    return {
        "status": hy_rule.status
    }


def set_hy_address(request):
    # 设置合约地址
    global hy_rule, sales
    hy_rule.get_receiving_area()
    if sales.receive_address["full"] in sales.receiving_area:
        return "已存在合约地址"
    hy_rule.set_reveieving_area(sales.receive_address)
    return {
        "status": hy_rule.status
    }


def set_ps_rule(request):
    # 设置配送地址
    global env, puser, sales, ps_rule
    ps_rule = DispatchingRule(env, puser)
    ps_rule.get_dispatching_rule()
    if sales.receive_address in ps_rule.dispatching_rule:
        return {
            "status": "已存在配送地址"
        }
    # 地址设置待定


def driver_bespeak(request):
    # 短途预约
    global auser, sales
    # 获取司机信息
    auser.get_driver_info()
    if auser.is_tag:
        return {
            "status": sales.status
        }
    # 获取配送规则
    sales.get_distribution_rules()
    if sales.is_tag:
        return {
            "status": sales.status
        }
    # 获取配送规则车牌号
    sales.get_distribution_rules_car()
    if sales.is_tag:
        return {
            "status": sales.status
        }
    # 配送单预约
    sales.distribution_sheet_bespeak()
    if sales.is_tag:
        return {
            "status": sales.status
        }


def baspeak_audit(request):
    # 短途预约审核
    global sales
    # 司机短途配送预约查询
    sales.distribution_sheet_bespeak_query()
    if sales.is_tag:
        return {
            "status": sales.status
        }
    # 配送单预约审核
    sales.distribution_sheet_bespeak_audit()
    return {
        "status": sales.status
    }


def driver_sign(request):
    # 短途预约签到
    global sales
    # 司机签到
    sales.distribution_sheet_signin()
    return {
        "status": sales.status
    }


def sales_order_allot(requset):
    # 订单分配
    global sales
    # 配送单分配
    sales.distribution_sheet_distribution()
    return {
        "status": sales.status
    }


def sales_order_allot_query(request):
    # 查询装车单的销售单
    global sales
    # 查询装车单的销售单
    sales.get_transport_order_sales()
    return {
        "status": sales.status
    }


def untread_order_audit(request):
    # 退回操作审核
    global sales
    sales.untread_order_audit()
    return {
        "status": sales.status
    }


def get_untread_transport_order(request):
    # 获取待退货的装车单
    global sales
    sales.get_untread_transport_order()
    return {
        "status": sales.status
    }


def get_store_info(request):
    # 获取仓库信息
    global env, puser, storehouse_dict
    store = Storehouse(env, puser, logger)
    store.get_all_storehouse()
    storehouse_dict = store.storehouse_dict
    print(f"获取仓库信息: {store.status}")
    return {
        "status": store.status
    }


def get_dispatching_rule(request):
    # 获取配送规则
    global env, puser, dispatching_rule
    rule = DispatchingRule(env, puser, logger)
    rule.get_dispatching_rule()
    dispatching_rule = rule.dispatching_rule
    return {
        "status": rule.status
    }


def get_treaty_config(request):
    # 获取合约配置
    global env, puser, hy_rule, zt_rule, one_hy_rule, two_hy_rule
    one_hy_rule = OneLevelTreatyRule(env, puser, logger)
    one_hy_rule.get_treaty_config()
    if one_hy_rule.code == 0:
        return {
            "status": one_hy_rule.status
        }
    one_hy_rule.get_receiving_area()
    if one_hy_rule.code == 0:
        return {
            "status": one_hy_rule.status
        }
    two_hy_rule = TwoLevelTreatyRule(env, puser, logger)
    two_hy_rule.get_treaty_config()
    if two_hy_rule.code == 0:
        return {
            "status": two_hy_rule.status
        }
    two_hy_rule.get_receiving_area()
    if two_hy_rule.code == 0:
        return {
            "status": two_hy_rule.status
        }
    if one_hy_rule.enableContractRoute:
        hy_rule = one_hy_rule
    elif two_hy_rule.enableContractRoute:
        hy_rule = two_hy_rule
    if one_hy_rule.enableProductRoute:
        zt_rule = one_hy_rule
    elif two_hy_rule.enableProductRoute:
        zt_rule = two_hy_rule

    return {
        "status": "获取合约配置成功"
    }


def get_cargo(request):
    # 获取货物信息
    global env, puser, cargo_dict, cargo, logger
    cargo = Cargo(env, puser, logger)
    cargo.get_cargo()
    cargo_dict = cargo.cargo_dict
    return {
        "status": "获取物料数据成功"
    }


def presell_plan_distribution(request):
    # 预售计划分配
    global sales
    sales.presell_plan_distribution()
    return {
        "status": sales.status
    }


def presell_plan_retrieve(request):
    # 预售计划回收
    global sales
    sales.presell_plan_retrieve()
    return {
        "status": sales.status
    }


def presell_plan_force_distribution(request):
    # 设置预售计划回收时间马上过期
    global sales
    sales.presell_plan_force_distribution()
    return {
        "status": sales.status
    }


def presell_plan_force_retrieve(request):
    # 预售计划超时回收释放
    global sales
    sales.presell_plan_force_retrieve()
    return {
        "status": sales.status
    }


def transport_query(request):
    # 装车单查询
    global puser, storehouse_dict, env, transport

    transports_no = request.POST.get('transport_no')
    print(f"装车单号：{transports_no}")
    transport = TransportOrder(
        puser, auser, transports_no, storehouse_dict, env)
    transport.transport_order_quest()
    return {
        "status": transport.status
    }


def transport_allot(request):
    # 配货
    global transport
    transport.transport_order_allot()
    return {
        "status": transport.status
    }


def transport_challenge(request):
    # 叫号
    global transport
    transport.get_transport_order_detail()
    if transport.queueStatusName != "允许进厂":
        print("未叫号，开始叫号")
        transport.transport_order_enter_auth()
    return {
        "status": transport.queueStatusName
    }


def transport_into_factory(request):
    # 查询进厂大门s
    global transport
    transport.transport_order_quest()
    transport.transport_order_into_factory()
    return {
        "status": transport.status
    }


def first_loadometer(request):
    # 首次过磅
    global transport
    transport.transport_order_quest()
    transport.transport_order_first_loadmeter()
    return {
        "status": transport.status
    }


def loading(request):
    # 装车
    global transport
    transport.transport_order_quest()
    transport.transport_order_stowage()

    return {
        "status": transport.status
    }


def inspect(request):
    # 检查
    global transport
    transport.transport_order_quest()
    transport.transport_order_check_up()
    return {
        "status": transport.status
    }


def two_loadometer(request):
    # 二次过磅
    global transport
    transport.transport_order_quest()
    loadings = transport.loadings[0]
    transport.transport_order_second_loadmeter(loadings)
    return {
        "status": transport.status
    }


def two_loadomter_hand_movement(request):
    # 二次过磅手动抬杆
    global transport
    transport.transport_order_quest()
    loadings = transport.loadings[0]
    callbacksure = 1
    callCode = transport.loadings[0]["errorHandleCode"]
    transport.transport_order_second_loadmeter(
        loadings, callbacksure, callCode)
    return {
        "status": transport.status
    }


def out_of_factory(request):
    # 出厂
    global transport
    transport.transport_order_out_of_factory()
    return {
        "status": transport.status
    }


def out_of_factory_coerce(request):
    # 强制出厂
    global transport
    # transport.transport_order_out_of_factory_coerce()
    return {
        "status": "功能还未实现"
    }


def transport_order_arrival(request):
    # 到货
    global transport
    # transport.transport_order_arrival()
    return {
        "status": "功能还未实现"
    }


def transport_order_signfor(request):
    # 签收
    global transport
    transport.transport_order_signfor()
    return {
        "status": "功能还未实现"
    }


def freeze(request):
    # 冻结
    global transport
    transport.freeze_apply()
    return {
        "status": transport.status
    }


def freeze_audio(request):
    # 冻结申请审核
    global transport
    transport.freeze_apply_audit()
    return {
        "status": transport.status
    }


def freeze_affirm(request):
    # 冻结确认
    global transport
    transport.freeze_affirm()
    return {
        "status": transport.status
    }


def freeze_stowage_cancel(request):
    # 冻结取消
    global transport
    transport.freeze_stowage_cancel()
    return {
        "status": transport.status
    }


def freeze_loadometer(request):
    # 冻结二磅
    global transport
    transport.transport_order_quest()
    transport.freeze_loadometer()
    return {
        "status": transport.status
    }


def return_app_sign(request):
    # 司机签到
    global transport
    transport.return_app_sign()
    return {
        "status": transport.status
    }


def return_into_factory(request):
    # 退回进厂
    global transport
    transport.transport_order_quest()
    transport.return_info_factory()
    return {
        "status": transport.status
    }


def return_first_loadometer(request):
    # 退回首次过磅
    global transport
    transport.transport_order_quest()
    transport.return_first_loadometer()
    return {
        "status": transport.status
    }


def return_loading(request):
    # 退回装货
    global transport
    transport.transport_order_quest()
    transport.return_loading()
    return {
        "status": transport.status
    }


def return_inspect(request):
    # 退回检查
    global transport
    transport.transport_order_quest()
    transport.return_order_audit()
    return {
        "status": transport.status
    }


def return_two_loadometer(request):
    # 退回二次过磅
    global transport
    transport.transport_order_quest()
    transport.return_two_loadometer()
    return {
        "status": transport.status
    }


def return_out_of_factory_audit(request):
    # 退回出厂审核
    global transport
    transport.transport_order_quest()
    transport.return_out_of_factory_audit()
    return {
        "status": transport.status
    }


def return_out_of_factory(request):
    # 退回出厂
    global transport
    transport.transport_order_quest()
    transport.transport_order_out_of_factory()
    return {
        "status": transport.status
    }


def sales_reset(request):
    # 销售单重新判断
    global sales
    sales.sales_reset()
    if sales.code == 0:
        return sales.status
    sales.sales_order_query()
    if sales.code == 0:
        return sales.status
    return {
        "status": sales.status
    }


def get_driver_iphone(request):
    # 获取司机手机号
    global auser
    auser.get_driver_info(True)
    if auser.driver_phone == "":
        return {
            "status": auser.status
        }
    else:
        return {
            "status": auser.driver_phone
        }


def logistics_order_query(request):
    # 物流单查询
    global logistics, env, puser, auser, logger

    logistics_no = request.POST.get('logistics_order_no')
    print(f"物流单号：{logistics_no}")
    logistics = Logistics(env, puser, auser, logger, logistics_no)
    logistics.get_logistics_info()
    return {
        "status": logistics.status
    }


def get_logistics_order(request):
    global logistics
    logistics.get_logistics_plate_number_list()
    return {
        "cargo_list": [
            {
                "code": logistics["goodsNo"],
                "name": logistics["productName"],
                "spec": logistics["goodsSpec"],
                "surplus": logistics["residueCount"],
            } for logistics in logistics.logistics_info["details"]
        ],
        "plate_number_list": logistics.plate_number_list
    }


def create_transport_order(request):
    # 创建装车单
    global logistics, puser, auser
    if not auser:
        return {
            "status" "APP端未登录"
        }
    auser.get_driver_info()
    driver_id_card = auser.driver_id_card
    plate_number = request.POST.get('plate_number')
    goods_list = request.POST.get('goods_list')
    goods_list = json.loads(goods_list)
    logistics.create_transport_order(goods_list, plate_number, driver_id_card)
    return {
        "status": logistics.status
    }


def get_logistics_transport_order(request):
    # 获取物流单下的装车单列表
    global logistics
    logistics.get_logistics_transport_order()
    if logistics.code == 0:
        return {
            "code": logistics.code,
            "status": logistics.status,
        }
    else:
        return {
            "code": logistics.code,
            "transport_list": logistics.transport_list
        }
